const constant = require('../../config/constant.js')

var app = getApp()
Page({

  data: {
    goodslists: [],
    total: 0,
    checkedCount: 0
  },
  gocalc() {

    var ids = this.data.goodslists.map(r => {
      if (r.checked)
        return {
          id: r.id,
          guigeid:r.guige.id
        }
    })

    wx.navigateTo({
      url: `../calc/index?ids=${JSON.stringify(ids)}`
    })
  },
  checkall() {
    if (this.data.checkedCount === this.data.goodslists.length) {
      this.data.goodslists.forEach(r => {
        r.checked = false
      })
    } else {
      this.data.goodslists.forEach(r => {
        r.checked = true
      })
    }

    this.setData({
      goodslists: this.data.goodslists
    })

    this.calcTotal()
  },

  changeState(e) {
    // console.log(e.currentTarget.dataset.id)
    var obj = this.data.goodslists.find(r => r.id === e.currentTarget.dataset.id)

    obj.checked = !obj.checked

    this.setData({
      goodslists: this.data.goodslists
    })

    this.calcTotal()
  },
  changeCheckboxState(e) {
    console.log(e.detail.value)
  },
  calcTotal() {
    this.data.total = 0
    this.data.checkedCount = 0
    this.data.goodslists.forEach(r => {
      if (r.checked) {
        this.data.checkedCount++;
        this.data.total += r.count * r.guige.price
      }
    })

    this.setData({
      total: this.data.total,
      checkedCount: this.data.checkedCount
    })
  },

  jia(e) {
    var obj = this.data.goodslists.find(r => r.id === e.currentTarget.dataset.id)

    obj.count++

      this.setData({
        goodslists: this.data.goodslists
      })

    this.calcTotal()

  },
  jian(e) {
    var obj = this.data.goodslists.find(r => r.id === e.currentTarget.dataset.id)
    if (--obj.count < 1) obj.count = 1

    this.setData({
      goodslists: this.data.goodslists
    })
    this.calcTotal()
  },
  onShow: function(options) {
    wx.request({
      url: 'http://localhost:9999/shopcart',
      data: {
        userid: 'o4-1F4wWgRikPtXegV6_mrcFTvIU' // app.globalData.userInfo.openId
      },
      success: res => {

        var idlist = res.data.map(r => r.goodsid)

        wx.request({
          url: 'http://localhost:9999/getGoodsByIds',
          data: {
            ids: idlist
          },
          success: res => {
            console.log(res.data)

            this.setData({
              goodslists: res.data
            })

            this.calcTotal()
          }
        })

      }
    })

    // wx.getStorage({
    //   key: constant.CACHE_KEY.SHOP_CART,
    //   success: res => {
    //     this.data.shopcart_cache = JSON.parse(res.data)

    //     console.log(JSON.parse(res.data))
    //   },
    // })
  }

})